import {ChangeDetectorRef, Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, NavigationEnd, NavigationStart, Router} from '@angular/router';
import {DataService} from '../data.service';
import {filter} from 'rxjs/internal/operators/filter';
import {stringify} from 'querystring';

@Component({
  selector: 'app-goods',
  templateUrl: './goods.component.html',
  styleUrls: ['./goods.component.css']
})
export class GoodsComponent implements OnInit {
  // goods = [];
  menus = [];
  goods = [];
  @ViewChild('btns', {static: false}) btns;
  constructor(private router: Router, private ds: DataService, private cdr: ChangeDetectorRef, private route: ActivatedRoute ) {}

  onMenuClick(menu, index) {
    for (let i = 0; i < menu.children.length; i ++) {
      menu.children[i].classList.remove('active');
      if (i === index) {
        menu.children[i].classList.add('active');
      }
    }
    location.href = '/goods#name' + index;
    // this.router.navigate(['/goods-list'], {fragment: 'name7'});
  }
  onIncrease(event, price) {
    event.stopPropagation();
    const ele = event.target.previousSibling;
    ele.classList.remove('hidden');
    ele.previousSibling.classList.remove('hidden');
    const num = parseInt(ele.textContent, 10) + 1;
    ele.textContent = num + '';
    this.ds.sPrice.next({
      price: price,
      clientX: event.clientX,
      clientY: event.clientY,
    });
  }
  onDecrease(event, price) {
    event.stopPropagation();
    const ele = event.target.nextSibling;
    const num = parseInt(ele.textContent, 10) - 1;
    if ( num === 0 ) {
      ele.classList.add('hidden');
      event.target.classList.add('hidden');
    }
    if ( num < 0 ) {
      return;
    }
    ele.textContent = num + '';
    this.ds.sPrice.next({
      price: -price,
      clientX: event.clientX,
      clientY: event.clientY,
    });
  }
  ngOnInit() {
    this.goods = this.ds.data.goods;
    for (const good of this.goods) {
      this.menus.push(good.name);
    }
    // this.router.events.pipe(
    //  filter((x) => x instanceof NavigationEnd || x instanceof NavigationStart)
    // ).subscribe((e) => {
     // console.log(e);
    // });
  }

  onGoodDetail(food) {
    console.log(food);
    this.router.navigate(['/goodDetail'], {
      skipLocationChange: true,
      queryParams: {
        foods: JSON.stringify(food)
      }
    });
  }
}
